package com.oocl.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.oocl.dto.MerchantDTO;
import com.oocl.exception.APlatformOfflineException;

/**
 * @description: 负责 从 A 端获取 指定 uname 的最新状态信息
 * @author  XIEMI2
 * @date Jul 29, 2017 8:49:30 AM
 * @version 1.0
 */
public class URLConnectionUtil {
	private static final Logger logger = LogManager.getLogger();
	private static final String URL = PropertiesUtil.getProperties().getProperty("URL");

	/**
	 * 从 A 端 获取所有 审核通过且 在 白名单上的商家信息
	 * @param
	 * @return List<MerchantVO>
	 * @throws APlatformOfflineException 
	 * @throws IOException 
	 */
	public static List<MerchantDTO> getAllPassMerchant() throws APlatformOfflineException{
		List<MerchantDTO> merchantDTOs = null;
		try {
			merchantDTOs = new ArrayList<MerchantDTO>();
			URLConnection connection;
			URL url = new URL(URL);
			connection = url.openConnection();
			connection.setDoOutput(true); //允许设置参数
			connection.setRequestProperty("Accept-Encoding", "identity"); 
			HttpURLConnection hconConnection = (HttpURLConnection) connection;
			hconConnection.setRequestMethod("POST");

			int len = hconConnection.getContentLength();
			if(len != -1){
				System.out.println("len: "+len);
				InputStream inputStream = hconConnection.getInputStream();
				byte[] buf = new byte[len];
				inputStream.read(buf);
				inputStream.close();
				hconConnection.disconnect();
				String jsonStr = new String(buf);
				logger.info(" 从 A 端所获得的 json 字符串为： {}", jsonStr);
				merchantDTOs = JsonUtil.parserToDTOs(jsonStr);
			}else{
				hconConnection.disconnect();
				logger.info(" getAllPassMerchant 为空 ");
				return merchantDTOs;
			}
		}catch(APlatformOfflineException aPlatformOfflineException){
			throw new APlatformOfflineException("A 平台down了。");
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return merchantDTOs;
	}
}


